package io.renren.modules.doc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.doc.dao.EnumConfigDao;
import io.renren.modules.doc.entity.EnumConfigEntity;
import io.renren.modules.doc.service.EnumConfigService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("enumConfigService")
public class EnumConfigServiceImpl extends ServiceImpl<EnumConfigDao, EnumConfigEntity> implements EnumConfigService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String enumType = (String)params.get("enumType");
        String enumKey = (String)params.get("enumKey");

        QueryWrapper<EnumConfigEntity> queryWrapper = new QueryWrapper<EnumConfigEntity>();
        if(StringUtils.isNotBlank(enumType)){
            queryWrapper.eq("enum_type", enumType);
        }
        if(StringUtils.isNotBlank(enumKey)){
            queryWrapper.like("enum_key", enumKey);
        }
        queryWrapper.orderByAsc("order_num");

        IPage<EnumConfigEntity> page = this.page(
                new Query<EnumConfigEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<EnumConfigEntity> getEnumsByType(String enumType) {
        if(StringUtils.isBlank(enumType)){
            return null;
        }
        
        QueryWrapper<EnumConfigEntity> queryWrapper = new QueryWrapper<EnumConfigEntity>()
            .eq("enum_type", enumType)
            .orderByAsc("order_num");
            
        return this.list(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<EnumConfigEntity> enumConfigs) {
        if(enumConfigs != null && !enumConfigs.isEmpty()) {
            super.saveBatch(enumConfigs);
        }
    }

    @Override
    public List<String> getAllEnumTypes() {
        QueryWrapper<EnumConfigEntity> queryWrapper = new QueryWrapper<EnumConfigEntity>()
            .select("DISTINCT enum_type");
        
        return this.list(queryWrapper)
            .stream()
            .map(EnumConfigEntity::getEnumType)
            .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEnum(EnumConfigEntity enumConfig) {
        this.updateById(enumConfig);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteEnum(Long[] ids) {
        this.removeByIds(Arrays.asList(ids));
    }
}
